import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import './style.css'
import { useSettingsStore } from './stores/settings'
import { useClipboardStore } from './stores/clipboard'
import { useAppStore } from './stores/app'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'

const appWindow = WebviewWindow.getCurrent()

async function initApp() {
  const app = createApp(App)
  const pinia = createPinia()

  app.use(pinia)
  app.use(router)

  // Initialize stores
  const settingsStore = useSettingsStore(pinia)
  const clipboardStore = useClipboardStore(pinia)
  const appStore = useAppStore(pinia)

  await Promise.all([
    settingsStore.loadSettings(),
    clipboardStore.loadClipboardItems()
  ])

  // 初始化主题
  appStore.initTheme()

  // 启动剪切板监听
  await invoke('start_clipboard_monitor')

  // 监听剪切板变化事件
  await listen('clipboard-change', async (event: any) => {
    const content = event.payload as string
    if (!content || content.trim() === '') return

    // 检查是否超过最大数量限制
    if (clipboardStore.items.length >= settingsStore.maxItems) {
      // 从数组末尾开始查找第一条非收藏记录
      for (let i = clipboardStore.items.length - 1; i >= 0; i--) {
        const item = clipboardStore.items[i];
        if (!item.favorite) {
          // 找到非收藏记录，删除它
          await clipboardStore.deleteItem(item.id);
          break;
        }
      }
    }

    // 检查是否已存在相同内容
    const existingItem = clipboardStore.items.find(item => item.content === content)
    if (existingItem) {
      // 如果存在相同内容，删除旧的并添加到最前面
      // await clipboardStore.deleteItem(existingItem.id)
      // await clipboardStore.addItem(content)
      existingItem.timestamp = Date.now()
      await clipboardStore.updateItem(existingItem)
    } else {
      // 如果不存在，直接添加新内容
      await clipboardStore.addItem(content)
    }
  })

  // 注册唤醒快捷键
  await settingsStore.unregisterShortcut()
  await settingsStore.registerShortcut()

  // 监听Esc键
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      // 检查是否有编辑器打开
      const editor = document.querySelector('.clipboard-editor')
      if (!editor) {
        // 只有在没有编辑器打开时才关闭主窗口
        appWindow.close()
      }
    }
  })

  app.mount('#app')
}

initApp().catch(console.error)
